#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/8/20 下午3:30
# @Author  : Azrael.Bai
# @File    : log_for_pgsql.py
import psycopg2
import time
import json


class LogForPgSql(object):
    def __init__(self, table_name):
        self.conn = psycopg2.connect(database="logdata", user="work", password="haizhi2018", host="192.168.0.94",
                                     port="5432")
        self.cur = self.conn.cursor()
        self.table = table_name
        self.FAILED = 0
        self.SUCCESS = 1
        self.RETRY = 2
        self.ABORT = 3
        self.LIST = 0
        self.DETAIL = 1

    def __del__(self):
        self.conn.close()

    def record(self, **kwargs):
        # 必要的前置处理
        application_id = kwargs.get("application_id")
        task_time = kwargs.get("task_time", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
        batch_info = kwargs.get("batch_info") # 自定不重复的编号,不要带中文
        task_type = kwargs.get("task_type") # 列表页,0/详情页,1
        task_status = kwargs.get("task_status") # 成功标识:1,成功,2,重试,3,废弃,0,失败
        task_param = kwargs.get("task_param", {}) # 例:{"company":"北京海致星图科技有限公司", "province":"北京","topic_id":30,"site":"gsxt.gov.cn"}
        task_param = json.dumps(task_param)
        self.insert(application_id, batch_info, task_time, task_type, task_status, task_param)

    def insert(self, application_id, batch_info, task_time, task_type, task_status, task_param):
        query = "INSERT INTO {}(application_id,batch_info,task_time,task_type,task_status,task_param)VALUES('{}','{}','{}',{},{},'{}');".format(
            self.table, application_id, batch_info, task_time, task_type, task_status, task_param)
        print(query)
        self.cur.execute(query)
        self.conn.commit()


if __name__ == '__main__':
    # 关于application_id: 资产系统登记后会统一生成一个application_id,日志登记时填写该字符串即可
    log = LogForPgSql("crawler_log_table")
    log.record(application_id='OFFLINE-100000002', batch_info='100001',task_type=log.LIST, task_status=1,task_param={"company":"北京海致星图科技有限公司"})